<script setup lang="ts">
import { Assignment } from "../../index";

const props = defineProps<{ assignment: Assignment }>();

import { ref } from "vue";
import { ElMessage } from "element-plus";
import { updateAssignmentAPI } from "../../api/assignment";
import { getAllGradeAPI } from "../../api/user";

const grades = ref<{ id: number; title: string }[]>([]);

getAllGradeAPI()
  .then((response) => {
    if (response.status !== 200) {
      throw new Error("网络错误");
    }
    return response.data;
  })
  .then((result) => {
    grades.value = result.data;
  });

const title = ref<string>(props.assignment.title);
const deadline = ref<Date>(props.assignment.deadline);
const gradeID = ref<number>(props.assignment.gradeID);

const emits = defineEmits(["update-already"]);

const update = () => {
  updateAssignmentAPI({
    id: props.assignment.id,
    title: title.value,
    gradeID: gradeID.value,
    deadline: deadline.value,
  })
    .then((response) => {
      if (response.status !== 200) {
        throw new Error("网络错误");
      }
      return response.data;
    })
    .then((result) => {
      // console.log(result);
      if (result.code === 40101) {
        ElMessage.error("请登录管理员账号");
      }
      if (result.data) {
        ElMessage.success({
          message: "修改成功",
        });
        emits("update-already");
      }
    });
};
</script>

<template>
  <el-form :label-position="'top'">
    <el-form-item label="作业标题: ">
      <el-input type="text" v-model="title" />
    </el-form-item>
    <el-form-item>
      <el-select v-model="gradeID">
        <el-option
          v-for="item in grades"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-date-picker
        v-model="deadline"
        type="datetime"
        placeholder="请选择截止时间"
      />
    </el-form-item>
    <el-button type="primary" @click="update">修改</el-button>
  </el-form>
</template>

<style scoped></style>
